import axios from 'axios';
import {Toast} from "vant";
import store from './store'

/***
 * 如果token失效跳到首页
 * 会经过router拦截
 * 此时已把登录token删除 所以此时会被拦截去登录页
 */
/***
 * 初始化http请求拦截
 */
export function initHttpInterceptor(instance) {
    let isDoRedirect = false;
    instance.interceptors.request.use((v) => {
        return v;
    });
    instance.interceptors.response.use(
        async response => {
            if (response) {
                const {code, message} = response.data;
                if (code === 500) {
                    Toast.fail(message)
                    throw new Error(message);
                }
            }
            return response;
        },
        error => {
            if (error.response) {
                const {code, msg} = error.response.data;
                if (code !== 200) {
                    Toast.fail('请求失败');
                    throw new Error('请求失败');
                }
            }
            return Promise.reject(error.response.data)
        });
}

/***
 * 如果没有登录则不能访问其他路由
 */
export function initRouterInterceptor(router) {
    router.beforeEach((to, from, next) => {
        if (!to.meta.authValid) return next();
        const isLogin = sessionStorage.getItem("X-Access-Token") && Object.keys(store.state.userInfo).length;
        isLogin ? next() : next({path: '/login', query: {oldPath: to.fullPath}});
    });
}
